package com.novellotus.iov.carvice.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.novellotus.httploadingview.LoadingView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.activity.AddFailureActivity;
import com.novellotus.iov.carvice.activity.CarDetailActivity;
import com.novellotus.iov.carvice.activity.SearchCarActivity;
import com.novellotus.iov.carvice.adapter.CarListAdapter;
import com.novellotus.iov.carvice.bean.MqttListCarBean;
import com.novellotus.iov.carvice.bean.RxCarListBean;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.MyViewUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.novellotus.iov.carvice.view.PageView;
import com.orangegangsters.github.swipyrefreshlayout.library.RefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.RefreshLayoutDirection;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * A simple {@link Fragment} subclass.
 */
public class CarListFragment extends BaseFragment implements CarListAdapter.ClickItemInterface, RefreshLayout.OnRefreshListener, LoadingView.OnBtnClickListener, PageView.PageViewInterface {

    @BindView(R.id.pageView)
    PageView pageView;
    CarListAdapter carListAdapter;

    private final int PAGE_SIZE = 10;


    @Override
    View initRootView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_car_list, container, false);
    }

    @Override
    void init() {
        //pageView.setLoadFinish(false);
        pageView.initLoadingView(this);
        pageView.refreshLayout.setOnRefreshListener(this);
        pageView.setPageViewInterface(this);
        pageView.loadingView.setOnBtnClickListener(this);
        if (response != null) {
            MyUtils.logInformation("实例化");
            pageView.setTotalPage(response.getTotal(), PAGE_SIZE);
            pageView.setLoadCurrentPage(1);
            carListAdapter = new CarListAdapter(CarListFragment.this, response.getRecords());
            pageView.setBottomInterface(carListAdapter);
            pageView.setRecyclerViewAdapter(MyViewUtils.getLinearLayoutManager(getContext()), carListAdapter);

        }

    }

    /**
     * @param response 刷新列表
     */
    RxCarListBean response;

    public void initList(RxCarListBean response) {
        this.response = response;
        MyUtils.logInformation("init");
//        if (carListAdapter != null) {
//            pageView.setTotalPage(response.getTotal(), PAGE_SIZE);
//            pageView.setLoadCurrentPage(1);
//            carListAdapter = new CarListAdapter(CarListFragment.this, response.getRecords());
//            pageView.setBottomInterface(carListAdapter);
//            pageView.setRecyclerViewAdapter(MyViewUtils.getLinearLayoutManager(getContext()), carListAdapter);
//        }
    }

    /**
     * 刷新当前数据
     */
    public void updateList() {
        int beforeCount = pageView.currentPage * PAGE_SIZE;
        pageView.setLoadCurrentPage(1);
        getList(1, beforeCount);
    }


    /**
     * @param mqttListCarBean 刷新mqtt数据
     */
    public void updateSingleCar(MqttListCarBean mqttListCarBean) {
        carListAdapter.updateSingleCar(mqttListCarBean);
    }


    /**
     * 获取车辆列表
     */
    public void getList(int currentPate, int size) {
        Observable<BaseEntity<RxCarListBean>> observable = RetrofitFactory.getInstance().followVehicleList(SharedPreferencesUtils.getKey(getContext())[0], currentPate, size, "");
        observable.compose(RxSchedulers.<BaseEntity<RxCarListBean>>compose())
                .subscribe(new BaseObserver<RxCarListBean>(getContext()) {
                    @Override
                    public void onSuccess(RxCarListBean response) {
                        pageView.loadSuccess();
                        pageView.setTotalPage(response.getTotal(), PAGE_SIZE);
                        if (response.getCurrent() == 1) {
                            carListAdapter.update(response.getRecords());
                        } else {
                            carListAdapter.addData(response.getRecords());
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        pageView.loadFail(msg, true);
                        //   MyUtils.showToast(getContext(), msg);
                    }

                    @Override
                    public void onError(String msg) {
                        pageView.loadFail(msg, true);
                        //  MyUtils.showToast(getContext(), msg);
                    }

                });
    }

    @OnClick(R.id.rlt_search)
    void clickSearch() {
        openActivity(getActivity(), SearchCarActivity.class);
    }

    @Override
    public void openDetail(String plate, String vin, int type) {
        Bundle bundle = new Bundle();
        bundle.putString("plate", plate);
        bundle.putString("vin", vin);
        bundle.putInt("type", type);
        openForResultActivity(getActivity(), CarDetailActivity.class, bundle);
    }

    @OnClick(R.id.img_service)
    public void addService() {
        openActivity(getActivity(), AddFailureActivity.class);
    }

    /**
     * 数据加载失败，重新加载
     */
    @Override
    public void onReload() {
        pageView.setLoadCurrentPage(1);
        getList(pageView.currentPage, PAGE_SIZE);
    }


    /**
     * @param direction 下拉刷新
     */
    @Override
    public void onRefresh(RefreshLayoutDirection direction) {
        pageView.refreshData(direction);
    }

    /**
     * @param dataPage 上拉加载
     */
    @Override
    public void loadData(int dataPage) {
        getList(pageView.currentPage, PAGE_SIZE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
